   # -*- coding: utf-8 -*-
from getSize import nikeSize
from get_tid import get_tid
import requests
from payInfo import getemail
import re
import json
import urllib
import conf_file
import time
import random
import sys  
reload(sys)
sys.setdefaultencoding('utf-8')


def nike(spurl):
	"""
	1.商品抢购
	2.填写收货信息
	3.生成订单
	4.提取付款链接和订单编号
	"""
	#拉取尺码
	#print spurl

	t = random.randint(1,30)
	print 'get size Random waiting time:',t #等待时间
	time.sleep(t) #1-30s之间随机等待
	size_valueList = nikeSize(spurl)['allSize']
	#print '有货尺码:',size_valueList
	print 'OK'
	if size_valueList[1] != []:
		#拉取用户
		params=urllib.urlencode({'tid':tid,'taskrelid':taskrelid})
		r=requests.post(conf_file.path_url+'/Rpc/taskuser',headers=Head,data=params)
		#print r.text.decode('unicode-escape')
		print 'OK1'
		# print type(json.loads(r.text)['code'])
		# print json.loads(r.text)['code']
		if json.loads(r.text)['code'] == 4001:
			print "No user data" 

		elif json.loads(r.text)['code'] is 1:
			try:
				u_id=json.loads(json.loads(r.text)['data']['u_id'])
				t_id=json.loads(json.loads(r.text)['data']['t_id'])
			
			
				data=json.loads(r.text)['data']
				addressremark=data['u_field']['addressremark']
				registerinfo={'mobile':data['mobile'],
							  'username':data['u_name'],
							  'password':data['u_pwd'],
							  'birthday':data['birthday']
							  }
				addressinfo={ 'firstname':data['firstname'],
							  'region':addressremark['province'].encode('utf8'),
							  'city':addressremark['city'].encode('utf8'),
							  'district':addressremark['district'].encode('utf8'),
							  'street':data['u_address'], #街道不能超过35个字符
							  'address2':addressremark['street'].encode('utf-8'),
							  'delivery_memo':data['u_address'].encode('utf-8'),
							  'postcode':data['u_addresscode'].encode('utf8'),
							  'mobile':data['mobile'].encode('utf8'),
							  'email':data['u_eamil'],
							  }

				address1=addressinfo['street'][:33]
				address2=addressinfo['street'][33:]

				zone={'北京市':'CN-11','天津市':'CN-12','河北省':'CN-13','山西省':'CN-14','内蒙古自治区':'CN-15','辽宁省':'CN-21','吉林省':'CN-22','黑龙江省':'CN-23','上海市':'CN-31','江苏省':'CN-32','浙江省':'CN-33','安徽省':'CN-34','福建省':'CN-35','江西省':'CN-36','山东省':'CN-37','河南省':'CN-41','湖北省':'CN-42','湖南省':'CN-43','广东省':'CN-44','广西壮族自治区':'CN-45','海南省':'CN-46','重庆市':'CN-50','四川省':'CN-51','贵州省':'CN-52','云南省':'CN-53','西藏自治区':'CN-54','陕西省':'CN-61','甘肃省':'CN-62','青海省':'CN-63','宁夏回族自治区':'CN-64','新疆维吾尔自治区':'CN-65'}
				region_id=zone[addressinfo['region']]
				print region_id


				## 登陆
				session=requests.Session()
				loginUrl='https://unite.nikecloud.com/login?locale=ch_CN&backendEnvironment=identity'
				data={  'client_id': "PbCREuPr3iaFANEDjtiEzXooFl7mXGQ7",
						'grant_type': "password",
						'password': registerinfo['password'],
						'username': addressinfo['email'],
						'ux_id': "com.nike.commerce.snkrs.web"}

				head={  'referer':spurl,
					'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36',
					'content-type':'text/plain'
					}

				loginResp=session.post(loginUrl,headers=head,data=json.dumps(data),verify=False)

	

				access_token=json.loads(loginResp.text)['access_token']
				print access_token

				##购买
				### 获取商品信息
				print 'get goods info...'
				spHead = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36',
						  'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
						  'referer':spurl,
						  'host':'www.nike.com'}
				sp_Resp =session.get(spurl,headers=spHead,verify=False)
				#print sp_Resp.text

	

				sptitle = re.search(r'"fullTitle":"(.*?)"',sp_Resp.text).group(1)
				productid = re.search(r'"product":{"id":"(.*?)"',sp_Resp.text).group(1)
				build = re.search(r"'build', '(.*?)'",sp_Resp.text).group(1)
				style = re.search(r'"style":"(.*?)"',sp_Resp.text).group(1)
				color = re.search(r'"colorCode":"(.*?)"',sp_Resp.text).group(1)
				print build,productid


				## 开始购买
				headers = {
						   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0',
						   'Accept': 'application/json',
						   'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
						   'Accept-Encoding': 'gzip, deflate, br',
						   'Content-Type': 'application/json; charset=UTF-8',
						   'Authorization': 'Bearer '+ str(access_token),
						   'Origin': 'https://www.nike.com',
						   'Connection': 'keep-alive'}


				#获取部分信息
				idurl = 'https://api.nike.com/payment/preview_results/v2/'
				checkoutid = requests.get(url=idurl,verify=False).json()['error_id']
				paymentid = requests.get(url=idurl,verify=False).json()['error_id']
				print checkoutid,paymentid

				# #获取任务状态 
				params=urllib.urlencode({'taskrelid':taskrelid,'tid':tid})
				r=requests.post(conf_file.path_url+'/Rpc/getTaskStatus',headers=Head,data=params)
				status_code=int(json.loads(r.text)['data']['status'])
				if status_code == 4: #对比任务状态
					sizeValue=random.sample(size_valueList[1],1)[0] #随机一个尺码
					size = size_valueList[0][size_valueList[1].index(sizeValue)] #通过sizeValue的索引值找到用户看到的size
					print 'size info:',sizeValue,size
					post_data = {"request":{"email":addressinfo['email'],"country":"CN","currency":"CNY","locale":"zh_CN","channel":"SNKRS","clientInfo":{"deviceId":"0400R9HVeoYv1gsNf94lis1ztnqv7CRnBjGO6/Ao2WE9gwpcE7v8aPDcWlOv5uA0UdlgseU3hf6ZgJHVGVmGHhZkVg779SPfw9jg/bn+kus6mYbBOmoLto4X8btxUT7HF5Mfhlz5wlRFwWJi0FRulruXQQGCQaJkXU7G/xCx87H3fYLqtP6CELnsH2G/cdkIMFbm6Yf0/pTJUUzbuPzsQkRu5wydKgnOIDKXq4HnEqNOos1c6njJgQh/4uWPf9I5I43RRL7fOkkwV0dTsyiI82NHxcfuqPY9fpixLEzP4TAbNLx4B5Y+hlUTFU590nH6wX2EIJPl7taneAp+euwBRWG3oPxIPhWfkls2Dvmh2Ql/4ZmxrGle/ZqF1WSwCPCGIJ9ojofZbR2X0CLQi4PDljQGTZxyTYzWRQCIYmH70/9WYFgrFNC6lStdnvLrIbcVhbjA6CiAMtmPSSvD4TWhv78VEIne56x7fyVRlv/nuXQXQGvX0gKDOFP1a/PoP5g1QwsR6HPyNaJmTDai9XF2InkrPPEFszfR7TVeYTtUNo5lYHxObL5PzR66nFRQJiixP4LBaxBeNabCoO0mlBgAVSsOVyyofExHIwDdyG4AHEbU3IynXrhcnO4UgCiP3k08ruO2MV2HeXfsIpcBAz+JqnVObFzqeMmBCH/ieLkYYw7gRCdLh7h/QYTtLeSWd2Bz5ubbq4HnEqNOos1/ARf3yJm6ITKx4PQbX9OHEQi+wlGoZ8WFk9C8+4pEn8Th1HyH9FgHkp62yUjciLEbPmkId7X9UBOd0/ewrrCpRONsrNmlQ0HEpvsUb5+Jr8qK4pvupFpLCfh5mpkjbY8JuvK70bwBpMhq5G0JDAEfjhfTyMu2WPU60XI1EZKVyZnHyH/spdP176ZigQa7PSc/NzbdUf1XOt8yWPvgXmLrlec+amWueJGZ4qN4QLKvqUV6ETiAWTGOqSKmGE9zDPF+pgCd2Ux7tt1mhTHKQ7jy9YMNjqOzgRW6psCbeWacXO7lr/RXFLtCT3fKaEmHgdZTpQDsI1l5pRcWvEsMdd2+SxT8V+5FRjwlPEdtOvY8eD35tOUw6jrqNh+QxW8Z/i97IRumGgXkYUn43/pPHCmdlDbGqeGq16udizKgcTSmkq/0eVBwKCbFEPNOpFjI2/6EOwkchN4u2PRWt+WNpGvHIi7SoUevORpROJ9qSFv+eJR3sCFSNJMUA7mWm5ddG/uXwr835+t4m0pJOwycmYRLIEgMnyu7KEs="},
											"items":[{"id":productid,
											"skuId":sizeValue,
											"quantity":1,
											"recipient":{"firstName":addressinfo['firstname'][1:],"lastName":addressinfo['firstname'][0:1]},
											"shippingAddress":{"address1":addressinfo['street'],
															   "address2":addressinfo['address2'],
															   "city":addressinfo['city'],
															   "state":region_id,
															   "postalCode":addressinfo['postcode'],
															   "county":addressinfo['district'],
															   "country":"CN"},
											"contactInfo":{"email":addressinfo['email'],"phoneNumber":addressinfo['mobile']},
											"shippingMethod":"GROUND_SERVICE"}]}}

					html1 = session.put(url='https://api.nike.com/buy/checkout_previews/v2/' + checkoutid,headers=headers,data=json.dumps(post_data),verify=False)
					#print html1.content
					jobs =  html1.json()['links']["self"]["ref"]
					#print 'get paidui info'

					# html2 = session.get(url='https://api.nike.com' + jobs,headers=headers,verify=False) 
					# total = html2.json()['response']['totals']['total']
					# spPrice = html2.json()['response']['shippingGroups'][0]['items'][0]['priceInfo']['price']
					# discount = html2.json()['response']['shippingGroups'][0]['items'][0]['priceInfo']['discount']
					# priceChecksum = json.loads(html2.text)['response']['priceChecksum']

					while True:
						t = random.randint(1,60)
						print 'get paidui info Random waiting time:',t #等待时间
						time.sleep(t) #1-30s之间随机等待
						html2 = session.get(url='https://api.nike.com' + jobs,headers=headers,verify=False)
			
						try :
							print html2.json()
							html2.json()['response'] 
							total = html2.json()['response']['totals']['total']
							spPrice = html2.json()['response']['shippingGroups'][0]['items'][0]['priceInfo']['price']
							discount = html2.json()['response']['shippingGroups'][0]['items'][0]['priceInfo']['discount']
							priceChecksum = json.loads(html2.text)['response']['priceChecksum']
							break
						except:
							try:
								html2.json()['error']
								break 
							except:
								print 'The request failed and the request was repeated'

					#上面的循环跳出来有2种原因分别处理
					try :
						html2.json()['error']
					except:
						pay_url = 'https://api.nike.com/payment/preview/v2/'
						pay_data = {"checkoutId":checkoutid,"total":1,"currency":"CNY","country":"CN",
									"items":[{"productId":productid,
											  "shippingAddress":{ "address1":addressinfo['street'],
																  "address2":addressinfo['address2'],
																  "city":addressinfo['city'],
																  "state":region_id,
																  "postalCode":addressinfo['postcode'],
																  "county":addressinfo['district'],
																  "country":"CN"}}],
									"paymentInfo":[{"id":paymentid,
													"billingInfo":{"name":{"firstName":addressinfo['firstname'][1:],"lastName":addressinfo['firstname'][0:1]},
									"address":{"address1":addressinfo['street'],
											   "city":addressinfo['city'],
											   "state":region_id,
											   "postalCode":addressinfo['postcode'],
											   "county":addressinfo['district'],
											   "country":"CN"},
									"contactInfo":{"phoneNumber":"+86"+addressinfo['mobile'], #不确定这里是绑定的手机号还是收货手机号
												   "email":addressinfo['email']}},"type":"Alipay"}]}
						pay_html = session.post(url=pay_url,headers=headers,data=json.dumps(pay_data),verify=False)
						#print pay_html.json()
						paymenpreview = pay_html.json()['links']['self']['ref']
						paymenpreview_url = 'https://api.nike.com' + paymenpreview
						paymenpreviewjobs = session.get(url=paymenpreview_url,headers=headers,verify=False)
						paymentToken = paymenpreviewjobs.json()['id']
						# print paymentToken
						# print paymenpreviewjobs.json()
						
						#排队抽签
						#重改
						# 获取launchid
						url = 'https://api.nike.com/launch/launch_views/v2/?filter=productId('+productid+')'
						resp = session.get(url,headers=headers,verify=False)
						#print resp.text
						launchid = json.loads(resp.text)['objects'][0]['id']
						print launchid


						url = 'https://api.nike.com/launch/entries/v2/'
						data = {
							"launchId":launchid,
							"skuId": sizeValue,
							"locale": "zh_CN",
							"currency": "CNY",
							"deviceId":"0400R9HVeoYv1gsNf94lis1ztnqv7CRnBjGO6/Ao2WE9gwpcE7v8aPDcWlOv5uA0UdlgseU3hf6ZgJHVGVmGHhZkVg779SPfw9jg/bn+kus6mYbBOmoLto4X8btxUT7HF5Mfhlz5wlRFwWJi0FRulruXQQGCQaJkXU7G/xCx87H3fYLqtP6CELnsH2G/cdkIMFbm6Yf0/pTJUUzbuPzsQkRu5wydKgnOIDKXq4HnEqNOos1c6njJgQh/4uWPf9I5I43RRL7fOkkwV0dTsyiI82NHxcfuqPY9fpixLEzP4TAbNLx4B5Y+hlUTFU590nH6wX2EIJPl7taneAp+euwBRWG3oPxIPhWfkls2Dvmh2Ql/4ZmxrGle/ZqF1WSwCPCGIJ9ojofZbR2X0CLQi4PDljQGTZxyTYzWRQCIYmH70/9WYFgrFNC6lStdnvLrIbcVhbjA6CiAMtmPSSvD4TWhv78VEIne56x7fyVRlv/nuXQXQGvX0gKDOFP1a/PoP5g1QwsR6HPyNaJmTDai9XF2InkrPPEFszfR7TVeYTtUNo5lYHxObL5PzR66nFRQJiixP4LBaxBeNabCoO0mlBgAVSsOVyyofExHIwDdyG4AHEbU3IynXrhcnO4UgCiP3k08ruO2MV2HeXfsIpcBAz+JqnVObFzqeMmBCH/ieLkYYw7gRCdLh7h/QYTtLeSWd2Bz5ubbq4HnEqNOos1/ARf3yJm6ITKx4PQbX9OHEQi+wlGoZ8WFk9C8+4pEn8Th1HyH9FgHkp62yUjciLEbPmkId7X9UBOd0/ewrrCpRONsrNmlQ0HEpvsUb5+Jr8qK4pvupFpLCfh5mpkjbY8JuvK70bwBpMhq5G0JDAEfjhfTyMu2WPU60XI1EZKVyZnHyH/spdP176ZigQa7PSc/NzbdUf1XOt8yWPvgXmLrlec+amWueJGZ4qN4QLKvqUV6ETiAWTGOqSKmGE9zDPF+pgCd2Ux7tt1mhTHKQ7jy9YMNjqOzgRW6psCbeWacXO7lr/RXFLtCT3fKaEmHgdZTpQDsI1l5pRcWvEsMdd2+SxT8V+5FRjwlPEdtOvY8eD35tOUw6jrqNh+QxW8Z/i97IRumGgXkYUn43/pPHCmdlDbGqeGq16udizKgcTSmkq/0eVBwKCbFEPNOpFjI2/6EOwkchN4u2PRWt+WNpGvHIi7SoUevORpROJ9qSFv+eJR3sCFSNJMUA7mWm5ddG/uXwr835+t4m0pJOwycmYRLIEgMnyu7KEs=",
							"checkoutId": checkoutid,
							"postpayLink": spurl.split('https://www.nike.com')[1]+"?LEStyleColor="+style+"-"+color+"&LEPaymentType=AliPay",
							"shipping": {
								"recipient": {
									"firstName":addressinfo['firstname'][1:],
									"lastName":addressinfo['firstname'][0:1],
									"email": addressinfo['email'],
									"phoneNumber": addressinfo['mobile']
								},
								"address": {
									"address1": addressinfo['street'],
									"city": addressinfo['city'],
									"state": region_id,
									"postalCode": addressinfo['postcode'],
									"country": "CN",
									"county": addressinfo['district'],
								},
								"method": "GROUND_SERVICE"
							},
							"priceChecksum":priceChecksum,
							"paymentToken":paymentToken,
							"channel": "SNKRS"
						}

						#排队请求
						resp = session.post(url,headers=headers,data=json.dumps(data),verify=False)
						print resp.text
						print resp.status_code
						try:
							entries_url = json.loads(resp.text)['links']['self']['ref']
							resp = session.get(url,headers=headers,verify=False)
							#print resp.text
							print resp.status_code

							#排队视图
							url = 'https://api.nike.com/launch/launch_views/v2/'+launchid
							resp = session.get(url,headers=headers,verify=False)
							#print resp.text
							print resp.status_code

							# #产品
							url = 'https://api.nike.com/merch/products/v2/'+productid
							resp = session.get(url,headers=headers,verify=False)
							#print resp.text
							print resp.status_code

							#排队请求
							url = 'https://api.nike.com'+entries_url
							resp = session.get(url,headers=headers,verify=False)
							print resp.text

							# 排队中
							while True:
								t = random.randint(60,100)
								print 'get email info Random waiting time:',t #等待时间
								time.sleep(t)
								info = getemail(addressinfo['email'],registerinfo['password'])
								if info !='':
									qrcode_Url = info['qrcode_Url']
									order_id = info['orderNumber']
									#返回订单数据
									goods_attribute=json.dumps({'sytle':'','color':'','size':size})       
									orderInfo={'stid':stid,'u_id':u_id,'t_id':t_id,'orderNumber':order_id,'payurl':qrcode_Url,'taskrelid':taskrelid,'sptitle':sptitle,'spPrice':spPrice,'qty':'1','discount':discount,'yunFei':'','total':total,'goods_attribute':goods_attribute,'time':''}           
									params=urllib.urlencode(orderInfo)
									r=requests.post(conf_file.path_url+'/Rpc/createSignOrder',headers=Head,data=params)
									#print r.text
									break
								
						except:
							print 'You can not rush now'
						

					#释放用户
					params = urllib.urlencode({'tid':t_id,'uid':u_id})
					r=requests.post(conf_file.path_url+'/Rpc/releaseUser',headers=Head,data=params)
					print r.text
					

				else:
					print 'Task status change end task'
					# 任务结束释放用户
					params = urllib.urlencode({'tid':t_id,'uid':u_id})
					r=requests.post(conf_file.path_url+'/Rpc/releaseUser',headers=Head,data=params)
					print r.text

				
			except:
				print 'The program reports any exceptions and the user is released'
				#print e.message
				# 任务结束释放用户,#程序报任何异常，用户释放
				params = urllib.urlencode({'tid':t_id,'uid':u_id})
				r=requests.post(conf_file.path_url+'/Rpc/releaseUser',headers=Head,data=params)
				print r.text	

	else:
		print 'The goods sold out'




if __name__ == '__main__':

	while True:
		try:
			#获取团队id
			t_id=get_tid()
			print t_id
			#拉任务
			if t_id != '':
				Head={'User-Agent':'FLASHSALE',
						   'Referer': 'http://store.nike.com/cn/zh_cn/',
						   'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
						   'X-Requested-With':'XMLHttpRequest'}
				params=urllib.urlencode({'type':2,'tid':t_id}) #type任务类型
				r=requests.post(conf_file.path_url+'/Rpc/planTask',headers=Head,data=params)

				#print r.text.decode('unicode-escape')
				if json.loads(r.text)['code'] is 1 and json.loads(r.text)['data'] !=[] :
					taskrelid=json.loads(r.text)['data'][0]['task_relid']
					tid=json.loads(r.text)['data'][0]['t_id']
					#修改数据
					stid = json.loads(r.text)['data'][0]['site_id']
					spurl = json.loads(r.text)['data'][0]['task_url']
					#print '商品链接:',spurl
					
					#选择抢购平台
					head = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36',
						   'Referer': 'https://www.adidas.com.cn/customer/account/login/'}

					if stid == '1': # 苹果和naike不选尺码
						#print json.loads(r.text),type(json.loads(r.text))
						size_valueList=json.loads(json.loads(r.text)['data'][0]['rules'])['allSize']
					
					if stid == '3':
						nike(spurl)

					if stid == '1':
						size_valueList=size_valueList[1]
						adidas(spurl,size_valueList)
					
					if stid == '2':
						apple(spurl)
				
				else:
					print 'No task'


		except:
			pass
				